import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import Home from './pages/Home'
import TopicDetail from './pages/TopicDetail'
import TopicSquare from './pages/TopicSquare'
import MaterialCenter from './pages/MaterialCenter'
import MaterialDetail from './pages/MaterialDetail'
import Login from './pages/Login'
import UserManagement from './pages/UserManagement'
import ArticleCenter from './pages/ArticleCenter'
import ArticleDetail from './pages/ArticleDetail'
import IllustrationPage from './pages/IllustrationPage'
import IllustrationCenter from './pages/IllustrationCenter';
import IllustrationTaskDetail from './pages/IllustrationTaskDetail';
import './App.less'
import { useEffect, useState } from 'react'
import { http, API_PATH } from './utils/http/config'
import { message } from 'antd'

// 定义用户信息类型
interface UserInfo {
  username: string;
  email: string;
  role: string;
  display_name: string;
}

function App() {
  // 添加加载状态，避免闪烁
  const [isLoading, setIsLoading] = useState(true);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  // 添加用户信息状态
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const response = await http.get<UserInfo>(API_PATH.AUTH.ME);
      if (response.code === 0 && response.data) {
        setUserInfo(response.data);
        // 存储用户信息到sessionStorage，这样刷新页面时不会丢失
        sessionStorage.setItem('userInfo', JSON.stringify(response.data));
      } else {
        message.error('获取用户信息失败');
      }
    } catch (error) {
      console.error('获取用户信息错误:', error);
      // 如果获取用户信息失败，可能是令牌无效，清除登录状态
      localStorage.removeItem('access_token');
      localStorage.removeItem('token_type');
      setIsAuthenticated(false);
    } finally {
      setIsLoading(false);
    }
  };

  // 检查登录状态
  useEffect(() => {
    const checkAuth = () => {
      const token = localStorage.getItem('access_token');
      const authenticated = !!token;
      setIsAuthenticated(authenticated);

      // 如果已登录，尝试获取用户信息
      if (authenticated) {
        // 尝试从sessionStorage获取缓存的用户信息
        const cachedUserInfo = sessionStorage.getItem('userInfo');
        if (cachedUserInfo) {
          setUserInfo(JSON.parse(cachedUserInfo));
          setIsLoading(false);
        } else {
          // 没有缓存，则从API获取
          fetchUserInfo();
        }
      } else {
        setIsLoading(false);
      }
    };

    checkAuth();

    // 监听storage变化，以便在其他标签页登录/登出时更新状态
    window.addEventListener('storage', checkAuth);

    return () => {
      window.removeEventListener('storage', checkAuth);
    };
  }, []);

  // 加载中不显示内容
  if (isLoading) {
    return null;
  }

  return (
    <Router>
      <Routes>
        <Route path="/login" element={isAuthenticated ? <Navigate to="/" /> : <Login />} />
        <Route path="/" element={!isAuthenticated ? <Navigate to="/login" /> : <Home userInfo={userInfo} />} />
        <Route path="/topic-detail/*" element={!isAuthenticated ? <Navigate to="/login" /> : <TopicDetail />} />
        <Route path="/topic-square/*" element={!isAuthenticated ? <Navigate to="/login" /> : <TopicSquare />} />
        <Route path="/material-center/*" element={!isAuthenticated ? <Navigate to="/login" /> : <MaterialCenter />} />
        <Route path="/article-center/*" element={!isAuthenticated ? <Navigate to="/login" /> : <ArticleCenter />} />
        <Route path="/article-detail/:article_id" element={!isAuthenticated ? <Navigate to="/login" /> : <ArticleDetail />} />
        <Route path="/material-detail/*" element={!isAuthenticated ? <Navigate to="/login" /> : <MaterialDetail />} />
        <Route path="/illustration-center" element={!isAuthenticated ? <Navigate to="/login" /> : <IllustrationCenter />} />
        <Route path="/illustration/:article_id" element={!isAuthenticated ? <Navigate to="/login" /> : <IllustrationPage />} />
        <Route path="/illustration-task/:taskId" element={!isAuthenticated ? <Navigate to="/login" /> : <IllustrationTaskDetail />} />
        <Route
          path="/user-management"
          element={
            !isAuthenticated ?
              <Navigate to="/login" /> :
              userInfo?.role === 'admin' ?
                <UserManagement /> :
                <Navigate to="/" />
          }
        />
      </Routes>
    </Router>
  );
}

export default App
